import { useModel } from 'umi';

const useUserInfo = () => {
  const { initialState, setInitialState } = useModel('@@initialState');

  const setUserInfo = (userInfo: API.UserInfo) => {
    setInitialState({
      ...initialState,
      currentUser: {
        ...initialState!.currentUser!,
        user: {
          ...initialState!.currentUser!.user,
          ...userInfo,
        },
      },
    });
  };

  const refreshUserInfo = async (id = '') => {
    const userInfo = await initialState!.fetchUserInfo?.(id);
    if (!userInfo) return;
    setUserInfo(userInfo);
  };

  return {
    refreshUserInfo,
    setUserInfo,
    useInfo: initialState?.currentUser?.user,
  };
};

export default useUserInfo;
